﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PDFWriter
{
    public class PDFPageContent : INode
    {
        public const string CONTENT_TAG = "Content";
        public const string OBJECT_ID = "id";
        public const string GENERATION_ID = "GenID";
        public string ReferenceID
        {
            get;
            set;
        }
        private string xmlString = "<Content id=\"2\">"+
            "<Dictionary>"+
              "<DictionaryElement type=\"name\" value=\"length\">51</DictionaryElement>"+
            "</Dictionary>"+
            "<Stream>"+
              "BT\n"+
              "/F1 24 Tf\n" +
              "1 0 0 1 260 600 Tm\n" +
              "(Hello World)Tj\n" +
              "ET\n" +
            "</Stream>           "+
          "</Content> ";
        private XmlDocument reader = new XmlDocument();

        public PDFPageContent(string xmlString)
        {
            this.xmlString = xmlString;
            reader.LoadXml(xmlString);
        }

        public PDFPageContent()
        {
            reader.LoadXml(xmlString);
        }

        public PDFObject GetPDFObject()
        {
            return GetPDFObjects()[0];
        }

        public List<PDFObject> GetPDFObjects()
        {
            return new List<PDFObject>(){new PDFObject() { Text = ProcesXML(), ObjectID = ReferenceID, ObjectType = CONTENT_TAG+"s"}};
        }

        private string ProcesXML()
        {
            string result = null;
            string generationID = null;
            if (reader.FirstChild.Name == CONTENT_TAG)
            {
                foreach (XmlNode node in reader.FirstChild.ChildNodes)
                {
                    result += Utility.GetPDFString(node.OuterXml);    
                }
                
                if (reader.FirstChild.Attributes[OBJECT_ID].Value != null)
                {
                    generationID = reader.FirstChild.Attributes[OBJECT_ID].Value;
                    if (reader.FirstChild.Attributes[GENERATION_ID] != null)
                    {
                        generationID += reader.FirstChild.Attributes[GENERATION_ID].Value;
                    }
                    else
                    {
                        generationID += " 0";
                    }

                }
                ReferenceID = generationID + " R";
                result = generationID + " obj\n" + result + "endobj";
            }
            return result;
        }
    }
}
